﻿using AutoMapper;
using BasicData.API.Write.Application.Commands;
using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infrastructure.interfaces;
using MediatR;
using System.Transactions;

namespace BasicData.API.Write.Application.CommandHandlers
{
  
    public class CreateChanAllCommandHandler : IRequestHandler<CreateChanAllCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<ChanModel> baseRepository;

        public CreateChanAllCommandHandler(IMapper mapper, IBaseRepository<ChanModel> baseRepository)
        {
            this.mapper = mapper;
            this.baseRepository = baseRepository;
        }

        public async Task<APIResult<int>> Handle(CreateChanAllCommand request, CancellationToken cancellationToken)
        {
            var map = mapper.Map<List<ChanModel>>(request.chanModels);
            var r = 0;
            using (var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                     r = await baseRepository.AddAllAsync(map);
                    tran.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
            }
            return APIResult<int>.Success("保存成功", r);
        }
    }
}
